package com.project.m.api.busi.handlers.hicatcard.Inner;

import com.project.m.api.busi.config.BusiError;
import com.project.m.api.busi.db.entity.hicatcard.card.TCard;
import com.project.m.api.busi.db.service.hicatcard.card.CardService;
import com.project.m.api.busi.handlers.MerchantBizParamChecker;
import com.project.m.api.validates.ValidateParam;
import com.project.m.api.validates.ValidateRet;
import com.project.m.api.validates.ValidateUtil;
import com.project.m.api.busi.bean.inner.InnerCardListQueryReq;
import com.project.m.api.busi.bean.inner.InnerCardListQueryResp;
import com.project.m.api.common.biz.BizHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class InnerCardListQueryBizHandler extends MerchantBizParamChecker<InnerCardListQueryReq, InnerCardListQueryResp>
        implements BizHandler<InnerCardListQueryReq, InnerCardListQueryResp> {

    private final Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    CardService cardService;

    @Override
    public InnerCardListQueryResp handle(InnerCardListQueryReq bizRequest) throws Exception {

        InnerCardListQueryResp bizResp = new InnerCardListQueryResp();

        try {
            ValidateRet vRet = checkParam(bizRequest, bizResp);
            if (!vRet.isValid()) {
                return bizResp;
            }

            List<TCard> cardList = new ArrayList<TCard>();
            if (bizRequest.getAll().equals(InnerCardListQueryReq.ALL_TRUE)) {
                cardList = cardService.findByEnableOrderByOrdernumAsc(true);
            } else {
                cardList = cardService.findByEnableAndStatusOrderByOrdernumAsc(true, TCard.STATUS_SHOW);
            }

            bizResp.setResult_code(BusiError.ERR_CODE_SUCCESS);
            bizResp.setError_message("");
            bizResp.setCardList(cardList);
            return bizResp;

        } catch (Exception e) {
            logger.error("InnerCardListQueryBizHandler", e);
            bizResp.setResult_code(BusiError.ERR_CODE_DB_SAVE);
            bizResp.setError_message(BusiError.ERR_MSG_DB_SAVE);
            return bizResp;
        }

    }

    @Override
    public ValidateRet checkParam(InnerCardListQueryReq req, InnerCardListQueryResp resp) {
        ValidateRet vRet = super.checkParam(req, resp);
        if (!vRet.isValid())
            return vRet;
        List<ValidateParam> paramList = new ArrayList<ValidateParam>();
        vRet = ValidateUtil.validate(paramList);
        if (vRet == null) {
            vRet = new ValidateRet(true, "");
        }

        if (!vRet.isValid()) {
            resp.setResult_code(BusiError.ERR_CODE_PARAM_BAD_REQ);
            resp.setError_message(vRet.getErrMsg());
        }

        return vRet;
    }
}
